package pe.com.pgn.consolidadorventas.servidorestacion.ws.security;

import java.util.HashSet;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

import org.apache.log4j.Logger;

import pe.com.pgn.consolidadorventas.servidorestacion.ws.security.service.WsSeguridadService;

import com.sun.xml.wss.ProcessingContext;
import com.sun.xml.wss.XWSSProcessor;
import com.sun.xml.wss.XWSSecurityException;

public class SecurityHandler implements SOAPHandler<SOAPMessageContext> {

	XWSSProcessor securityProcessor = null;
	WsSeguridadService wsSeguridadService;
		
	static Logger logger = Logger.getLogger(SecurityHandler.class);

	public SecurityHandler() {
	}

	/**
	*  Recuperamos el bloque header.
	*/
	public Set<QName> getHeaders() {
		final QName securityHeader = new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "Security", "wsse");
		final HashSet<QName> headers = new HashSet<QName>();
		headers.add(securityHeader);
		return headers;
	}

	public boolean handleFault(final SOAPMessageContext messageContext) {
		return true;
	}

	public void close(final MessageContext messageContext) {
	}
	
	public boolean handleMessage(SOAPMessageContext messageContext) {
    	 return secureServer(messageContext);
    }
	
	//Funcion de seguridad
	private boolean secureServer(SOAPMessageContext soapMessageContext){
		
		  try {
	          //  System.setProperty("com.sun.xml.ws.fault.SOAPFaultBuilder.disableCaptureStackTrace","false");
			  	boolean outMessageIndicator = (Boolean) soapMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
	            if (!outMessageIndicator) {
	                XWSSProcessor xwssProcessor = SecurityConfigProcessorFactory.getXWSSProcessor(wsSeguridadService);
	                SOAPMessage message = soapMessageContext.getMessage();
	                ProcessingContext context = xwssProcessor.createProcessingContext(message);
	                context.setSOAPMessage(message);
	                SOAPMessage verifiedMsg = xwssProcessor.verifyInboundMessage(context);
	                soapMessageContext.setMessage(verifiedMsg);
	            }
	        } catch (XWSSecurityException ex) {
	        	logger.error(ex.getMessage());
	            throw new WebServiceException(ex.getMessage());
	        }
	        return true;

	}

	public void setSecurityProcessor(XWSSProcessor securityProcessor) {
		this.securityProcessor = securityProcessor;
	}

	public WsSeguridadService getWsSeguridadService() {
		return wsSeguridadService;
	}

	public void setWsSeguridadService(WsSeguridadService wsSeguridadService) {
		this.wsSeguridadService = wsSeguridadService;
	}
	
	


}